#include "../include/client_list.h"

ClientNode *client_list_init()
{
    ClientNode *head = malloc(sizeof(ClientNode));
    if(head == NULL)
    {
        printf("客户端链表头结点创建失败\n");
        exit(1);
    }
    head->next = NULL;
    return head;
}

void client_list_insert_tail(ClientNode *head, ClientNode *new_node)
{
    ClientNode *p = head;
    while(p->next != NULL)
    {
        p = p->next;
    }

    new_node->next = p->next;
    p->next = new_node;
}

ClientNode *find_client_by_sock(ClientNode *head, int sock)
{
    ClientNode *p = head->next;
    while(p != NULL && p->sock != sock)
    {
        p = p->next;
    }
    return p;
}

ClientNode *find_client_by_ip_and_port(ClientNode *head, char *ip, uint16_t port)
{
    ClientNode *p = head->next;
    while(p != NULL)
    {
        if(strcmp(p->ip, ip) == 0 && p->port == port)
        {
            return p;
        }
        p = p->next;
    }
    return p;
}

ClientNode *find_client_by_nickname(ClientNode *head, char *nickname)
{
    ClientNode *p = head->next;
    while(p != NULL && strcmp(p->nickname, nickname) != 0)
    {
        p = p->next;
    }
    return p;
}

void show_client(ClientNode *head)
{
    printf("目前已连接的客户端：\n");
    ClientNode *p = head->next;
    while(p != NULL)
    {
        printf("套接字：%d IP:%s 端口号：%hu\n", p->sock, p->ip, p->port);
        p = p->next;
    }
}

void remove_client_node(ClientNode *head, ClientNode *client)
{
    ClientNode *pre = head;
    while(pre->next != client)
    {
        pre = pre->next;
    }
    pre->next = client->next;
    client->next = NULL;
    close(client->sock);
    free(client);
}

void free_client_list(ClientNode *head)
{
    ClientNode *p = NULL;
    while(head->next != NULL)
    {
        p = head->next;
        head->next = p->next;
        p->next = NULL;
        close(p->sock);
        free(p);
    }
    free(head);
}